﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GoodStuff.Web.Controls
{
    /// <summary>
    /// After this button has been clicked, it become disabled to prevent a user for clicking the button more then one during
    /// a single roundtrip/postback to the server. You can specify a "WaitText". If not set, the Text-value will be used as
    /// button text during postback.
    /// </summary>
    /// <remarks>Overrides the 'onclick' attribute.</remarks>
    public class OneClickButton : System.Web.UI.WebControls.Button
    {
        protected override void OnPreRender(EventArgs e)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("if (typeof(Page_ClientValidate) == 'function') { ");
            //validationgroup?
            if (string.IsNullOrEmpty(this.ValidationGroup))
            {
                builder.Append("if (Page_ClientValidate() == false) {return false; }} ");
            }
            else
            {
                builder.Append(string.Concat("if (Page_ClientValidate('", this.ValidationGroup, "') == false) { return false; }} "));
            }
            if (!string.IsNullOrEmpty(this.ConfirmText))
            {
                builder.AppendFormat("if (confirm('{0}')) {{", this.ConfirmText);
            }
            builder.AppendFormat("this.value = '{0}';", string.IsNullOrEmpty(this.WaitText) ? this.Text : this.WaitText);
            builder.Append("this.disabled = true;");
            builder.Append(this.Page.ClientScript.GetPostBackEventReference(this, string.Empty));
            builder.Append(";");

            if (!string.IsNullOrEmpty(this.ConfirmText))
            {
                builder.Append("} else { return false;}");//confirm
            }

            base.Attributes["onclick"] = builder.ToString();
            base.OnPreRender(e);
        }

        [System.ComponentModel.Description("Text while waiting on postback-response")]
        public string WaitText { get; set; }

        [System.ComponentModel.Description("Text of a confirmation-popup")]
        public string ConfirmText { get; set; }
    }
}
